import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo } from '@/api/login'
const whiteList = ['/login','/forgetPassword','/deliver/dischargingGoods2','/purchase/purchaseSchedulingNew','/invite','/sale/workflowCheck'] // 不重定向白名单
// setToken('hn9vs7$f9e7bf6aa29359a5cd30564')
router.beforeEach((to, from, next) => {
  // next()
  NProgress.start();
  if (getToken()) {
    //console.log("111")
    if (whiteList.indexOf(to.path) !== -1) {
     // console.log("222")
      next();
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
     // console.log("333")
      getUseInfo().then((response) => {
        localStorage.setExpire('userInfo', response, 3600 * 1000 * 24);
        let userInfo = localStorage.getExpire('userInfo');
        store.dispatch('GetInfo').then(res => {
          let roleMenuCodes = userInfo.permissions ? userInfo.permissions : null;
          let ii = -1;
          let i = -1;
          if(to.meta.yzPath){
            ii = roleMenuCodes.findIndex((roleCode)=>{
              return to.path.indexOf(roleCode) != -1;
            });
          }else{
            i= roleMenuCodes.indexOf(to.name);
            // console.log("i",i)
          }
          if ((roleMenuCodes && i==-1 && ii == -1 && !to.meta.hidden)) { //路由无权限,直接访问首页
            next({path: '/index'})
          } else {
            // console.log(to.path+':'+ii)
            next()
          }
        })
      });
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      //console.log("666")
      next()
    } else {
      //console.log("777")
      let toUrl = '/login';
      next(toUrl);
      NProgress.done()
    }
  }
});

router.afterEach(() => {
  NProgress.done() // 结束Progress
});

function getUseInfo(){
  return new Promise((resolve, reject) => {
    let userInfo = localStorage.getExpire('userInfo');
    if(!userInfo){
      getUserInfo().then((res)=>{
        resolve(res)
      }).catch(()=>{
        reject(null)
      })
    }else{
      resolve(userInfo)
    }
  })
}


